<script setup lang="ts">
import { cva } from "class-variance-authority";
import { twMerge } from "tailwind-merge";
import ByIcon from "./ByIcon.vue";
import Taro from "@tarojs/taro";

const emits = defineEmits(["getphonenumber", "tap"]);

const {
  to,

  loading,
  disabled,
  variant = "solid",
  size = "default",
  type = "primary",
  rounded = true,
} = defineProps<{
  block?: boolean;

  // color?: string;
  fontSize?: string;
  colorStyle?: string;
  rounded?: boolean;

  variant?: "outline" | "solid" | "dashed" | "filled";
  type?: "primary" | "error" | "info" | "success";
  size?: "small" | "default" | "large";

  loading?: boolean;
  disabled?: boolean;

  icon?: string;
  iconColor?: string;

  iconSize?: number;
  openType?: string;

  to?: string;
}>();

/**
 * 处理button样式
 */
const varsBtn = cva(
  "relatice flex-center px-0 !w-full h-full text-[inherit] bg-[inherit] border-none shadow-none",
  {
    variants: {
      size: {
        small: "px-2",
        default: "px-4",
        large: "px-4",
      },
    },
  }
);

/**
 * 处理 ByButton 组件主体样式
 */
const vars = cva("relative py-0 inline-flex overflow-hidden", {
  variants: {
    //
    type: {
      primary: "type-primary",
      error: "type-error",

      info: "!text-[#888] bg-[#eee] border-[#eee]",
      // primary: "text-primary bg-primary border-primary",
      // primary: "bg-gradient-to-l from-[#222] to-[#5C590D] !text-[#C5FF10]",

      success: "!text-main bg-[#DEEF9E] border-[#DEEF9E]",
    },

    disabled: {
      true: "opacity-60",
    },

    //
    variant: {
      outline:
        "border border-solid border-[var(--type-color)] text-[var(--type-color)]",
      dashed:
        "border border-solid border-dashed border-[var(--type-color)] text-[var(--type-color)]",
      solid: "bg-[var(--type-color)] text-white",
      filled: "bg-[var(--type-color-bg)] text-[var(--type-color)]",
      text: "",
      link: "",
    },

    size: {
      small: "h-[40px] text-xs",
      default: "h-[80rpx]",
      large: "h-[120rpx] text-lg",
    },

    rounded: {
      true: "rounded-full",
      false: "rounded-md",
    },
  },
});

// 处理自定义按钮背景
// const varCusBg = cva(
//   "before:content-[' '] before:absolute before:bg-[green] before:-inset-[1px] before:rounded-[inherit]"
// );

const handleTap = () => {
  if (loading || disabled) return;

  if (to) {
    Taro.navigateTo({ url: to });
  } else {
    emits("tap");
  }
};
</script>

<template>
  <view
    :class="[block && 'w-full', twMerge(vars({ type, size, variant, rounded, disabled }), $attrs.class as string) ]"
    @tap="handleTap"
  >
    <button
      :openType="openType"
      :loading="loading"
      :class="[varsBtn({ size })]"
      @getphonenumber="$emit('getphonenumber', $event)"
      style="font-size: inherit"
    >
      <ByIcon
        class="mr-1"
        :name="icon"
        :color="iconColor"
        :size="iconSize"
        v-if="icon"
      />
      <slot />
    </button>
  </view>
</template>
